package vip.xiaomoli.courier.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import vip.xiaomoli.courier.component.CourierDBScanner;
import vip.xiaomoli.courier.util.CourierUtil;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
@ConditionalOnProperty(prefix = "courier", name = "cluster-scheme", havingValue = "Nacos")
@AutoConfigureAfter(CourierAutoConfiguration.class)
public class NacosClusterConfig {

    private static final Logger LOG = LoggerFactory.getLogger(NacosClusterConfig.class);

    @Value("${spring.application.name:}")
    private String applicationName;

    @PostConstruct
    @NacosInjected
    public void listen(NamingService namingService) {
        CourierDBScanner scanner = new CourierDBScanner();
        try {
            namingService.subscribe(applicationName, event -> {
                if (event instanceof NamingEvent) {
                    List<Instance> list = ((NamingEvent) event).getInstances();
                    List<String> clusterIps = new ArrayList<>();
                    for (int i=0; i<list.size(); i++) {
                        String ip = list.get(i).getIp();
                        clusterIps.add(ip);
                        if (ip.equals(CourierUtil.getLocalIP())) {
                            scanner.setPos(i);
                        }
                    }
                    scanner.setClusterIps(clusterIps);
                    LOG.info("Courier ips[{}]", CourierUtil.toString(clusterIps));
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }

}
